<template>
  <div class="template-edit-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button text @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>{{ isCreate ? '创建实验模板' : '编辑实验模板' }}</h2>
      </div>
      <div class="header-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">
          <el-icon><Check /></el-icon>
          保存
        </el-button>
      </div>
    </div>

    <!-- 标签页切换 -->
    <el-tabs v-model="activeTab" class="edit-tabs" @tab-change="handleTabChange">
      <!-- Tab 1: 表单视图 -->
      <el-tab-pane label="表单视图" name="form">
        <template #label>
          <span class="tab-label">
            <el-icon><Document /></el-icon>
            表单视图
          </span>
        </template>
        <div class="tab-content">
          <!-- 应用选择 -->
          <PresetSelector
            :default-application-id="defaultApplicationId"
            @application-change="handleApplicationChange"
          />

          <!-- 表单渲染器 -->
          <TemplateFormRenderer
            ref="formRendererRef"
            v-model="formData"
            :fields-config="TEMPLATE_FIELDS_CONFIG"
            :readonly="false"
            :selected-application-id="selectedApplicationId"
            :obs-presets="obsPresets"
            :image-presets="imagePresets"
            :resource-presets="resourcePresets"
            :nas-presets="nasPresets"
            @change="handleFormChange"
          />
        </div>
      </el-tab-pane>

      <!-- Tab 2: YAML 视图 -->
      <el-tab-pane label="YAML 视图" name="yaml">
        <template #label>
          <span class="tab-label">
            <el-icon><Notebook /></el-icon>
            YAML 视图
          </span>
        </template>
        <div class="tab-content yaml-view">
          <div class="yaml-toolbar">
            <el-alert
              type="info"
              :closable="false"
              show-icon
            >
              <template #title>
                <span style="font-size: 13px;">
                  您可以直接编辑 YAML 内容，保存时会自动同步到表单视图
                </span>
              </template>
            </el-alert>
          </div>
          <YamlEditor
            ref="yamlEditorRef"
            v-model="yamlContent"
            :readonly="false"
            @change="handleYamlChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  ArrowLeft,
  Check,
  Document,
  Notebook,
} from '@element-plus/icons-vue';
import TemplateFormRenderer from '@/components/TemplateFormRenderer/index.vue';
import YamlEditor from '@/components/YamlEditor/index.vue';
import PresetSelector from '@/components/PresetSelector/index.vue';
import { TEMPLATE_FIELDS_CONFIG } from '@/config/templateFieldsConfig';
import {
  parseYaml,
  stringifyYaml,
  extractFormData,
  buildYamlFromForm,
  validateFormData,
  deepClone,
  isEqual,
} from '@/utils/yamlTemplateParser';
import { useTemplateStore } from '@/stores/template';
import {
  getObsBucketPresets,
  getResourcePoolPresets,
  getImagePresets,
  getNasPresets,
} from '@/api/configPreset';
import { useAutoSave } from '@/composables/useAutoSave';

const route = useRoute();
const router = useRouter();
const templateStore = useTemplateStore();

const activeTab = ref('form');
const saving = ref(false);
const formRendererRef = ref(null);
const yamlEditorRef = ref(null);

// 判断是创建还是编辑
const isCreate = computed(() => !route.params.id);
const templateId = computed(() => route.params.id);

// 表单数据
const formData = ref({});
// YAML 字符串
const yamlContent = ref('');
// 原始完整数据（包含非交互字段）
const originalYamlData = ref(null);
// 上次同步的数据快照（用于判断是否需要同步）
const lastSyncSnapshot = ref({
  form: null,
  yaml: null,
});

// 是否正在同步（避免循环触发）
let isSyncing = false;

// 应用和配置预设数据
const selectedApplicationId = ref(null);
const defaultApplicationId = ref(null);
const obsPresets = ref([]);
const imagePresets = ref([]);
const resourcePresets = ref([]);
const nasPresets = ref([]);

// 自动保存/暂存功能
const draftKey = computed(() => {
  const name = formData.value?.name || 'unnamed';
  return `draft-template-${name}`;
});

const { clearDraft, recoverDraft } = useAutoSave(draftKey.value, formData, {
  enabled: true,
  autoRecover: false // 禁用自动恢复，在模板加载后手动恢复
});

// 初始化
onMounted(async () => {
  // 加载配置预设数据
  await loadConfigPresets();

  if (isCreate.value) {
    // 创建模式：加载默认模板
    await loadDefaultTemplate();
  } else {
    // 编辑模式：加载已有模板
    await loadTemplate();
  }

  // 模板加载完成后，尝试恢复草稿
  const recoveredData = recoverDraft();
  if (recoveredData) {
    Object.assign(formData.value, recoveredData);
  }
});

// 加载配置预设数据
async function loadConfigPresets() {
  try {
    const [obsRes, imageRes, resourceRes, nasRes] = await Promise.all([
      getObsBucketPresets({ active_only: false }),
      getImagePresets({ active_only: false }),
      getResourcePoolPresets({ active_only: false }),
      getNasPresets({ active_only: false }),
    ]);

    obsPresets.value = obsRes.items || [];
    imagePresets.value = imageRes.items || [];
    resourcePresets.value = resourceRes.items || [];
    nasPresets.value = nasRes.items || [];
  } catch (error) {
    console.error('加载配置预设失败:', error);
    ElMessage.warning('加载配置预设失败，部分功能可能不可用');
  }
}

// 加载默认模板
async function loadDefaultTemplate() {
  try {
    // 这里可以从后端获取默认模板，或者使用本地模板文件
    const response = await fetch('/templates/roma_xx_example.yaml');

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const yamlText = await response.text();

    // 检查返回的是否是 HTML（如果是说明文件未找到）
    if (yamlText.trim().startsWith('<!DOCTYPE') || yamlText.trim().startsWith('<html')) {
      throw new Error('模板文件未找到，请检查文件路径');
    }

    // 解析 YAML
    const yamlData = parseYaml(yamlText);
    originalYamlData.value = deepClone(yamlData);

    // 提取表单数据
    formData.value = extractFormData(yamlData, TEMPLATE_FIELDS_CONFIG);

    // 生成 YAML 字符串
    yamlContent.value = stringifyYaml(yamlData);

    // 初始化快照
    lastSyncSnapshot.value.form = deepClone(formData.value);
    lastSyncSnapshot.value.yaml = yamlContent.value;
  } catch (error) {
    console.error('加载默认模板失败:', error);
    ElMessage.error('加载默认模板失败: ' + error.message);
  }
}

// 加载已有模板
async function loadTemplate() {
  try {
    const template = await templateStore.getTemplateById(templateId.value);
    if (!template) {
      ElMessage.error('模板不存在');
      router.push('/experiment-templates');
      return;
    }

    // 设置默认选中的应用
    if (template.application_id) {
      defaultApplicationId.value = parseInt(template.application_id, 10);
      selectedApplicationId.value = parseInt(template.application_id, 10);
    }

    // 解析 YAML
    const yamlData = parseYaml(template.yaml_content);
    originalYamlData.value = deepClone(yamlData);

    // 提取表单数据
    formData.value = extractFormData(yamlData, TEMPLATE_FIELDS_CONFIG);

    // 生成 YAML 字符串
    yamlContent.value = template.yaml_content;

    // 初始化快照
    lastSyncSnapshot.value.form = deepClone(formData.value);
    lastSyncSnapshot.value.yaml = yamlContent.value;
  } catch (error) {
    console.error('加载模板失败:', error);
    ElMessage.error('加载模板失败');
  }
}

// 表单数据变化 -> 同步到 YAML
function handleFormChange(newFormData) {

  if (isSyncing) {
    return;
  }
  if (activeTab.value !== 'form') {
    return;
  }
  // 如果原始数据还未加载，跳过同步（避免在草稿恢复时出错）
  if (!originalYamlData.value) {
    return;
  }
  if (isEqual(newFormData, lastSyncSnapshot.value.form)) {
    return;
  }

  isSyncing = true;

  try {
    // 从表单数据构建完整 YAML 对象
    const newYamlData = buildYamlFromForm(
      newFormData,
      originalYamlData.value,
      TEMPLATE_FIELDS_CONFIG
    );

    // 转换为 YAML 字符串
    const newYamlContent = stringifyYaml(newYamlData);

    // 更新 YAML 内容
    yamlContent.value = newYamlContent;
    originalYamlData.value = deepClone(newYamlData);

    // 更新快照
    lastSyncSnapshot.value.form = deepClone(newFormData);
    lastSyncSnapshot.value.yaml = newYamlContent;
  } catch (error) {
    console.error('同步到 YAML 失败:', error);
  } finally {
    isSyncing = false;
  }
}

// YAML 内容变化 -> 同步到表单
function handleYamlChange(newYamlContent) {
  if (isSyncing) return;
  if (activeTab.value !== 'yaml') return;

  // 类型检查：确保传入的是字符串
  if (typeof newYamlContent !== 'string') {
    console.error('handleYamlChange: 期望字符串类型，实际类型:', typeof newYamlContent, '值:', newYamlContent);
    return;
  }

  // 检查是否真的变化了
  if (newYamlContent === lastSyncSnapshot.value.yaml) {
    return;
  }

  isSyncing = true;

  try {
    // 解析 YAML
    const newYamlData = parseYaml(newYamlContent);

    // 提取表单数据
    const newFormData = extractFormData(newYamlData, TEMPLATE_FIELDS_CONFIG);

    // 更新表单数据
    formData.value = newFormData;
    originalYamlData.value = deepClone(newYamlData);

    // 更新快照
    lastSyncSnapshot.value.form = deepClone(newFormData);
    lastSyncSnapshot.value.yaml = newYamlContent;
  } catch (error) {
    console.error('YAML 解析失败:', error);
    ElMessage.error('YAML 格式错误，请检查语法');
  } finally {
    isSyncing = false;
  }
}

// 标签页切换
function handleTabChange(tabName) {
  console.log('切换到标签页:', tabName);
}

// 处理应用选择变化
function handleApplicationChange(applicationId) {
  selectedApplicationId.value = applicationId;
  console.log('选择应用:', applicationId);
}

// 保存
async function handleSave() {
  // 验证表单数据
  const validation = validateFormData(formData.value, TEMPLATE_FIELDS_CONFIG);
  if (!validation.valid) {
    ElMessage.error(validation.errors[0].message);
    activeTab.value = 'form';
    return;
  }

  // 确认保存
  try {
    await ElMessageBox.confirm(
      '确定要保存此模板吗？',
      '确认保存',
      {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        type: 'info',
      }
    );
  } catch {
    return;
  }

  saving.value = true;

  try {
    // 构建最终的 YAML 数据
    const finalYamlData = buildYamlFromForm(
      formData.value,
      originalYamlData.value,
      TEMPLATE_FIELDS_CONFIG
    );

    const finalYamlContent = stringifyYaml(finalYamlData);

    if (isCreate.value) {
      // 验证必选字段
      if (!selectedApplicationId.value) {
        ElMessage.error('请选择应用');
        saving.value = false;
        return;
      }

      // 创建模板
      await templateStore.createTemplate({
        name: formData.value.name,
        description: formData.value.desc,
        yaml_content: finalYamlContent,
        application_id: selectedApplicationId.value,
        tags: [],
      });
      ElMessage.success('模板创建成功');
    } else {
      // 更新模板
      await templateStore.updateTemplate(templateId.value, {
        description: formData.value.desc,
        yaml_content: finalYamlContent,
        application_id: selectedApplicationId.value,
      });
      ElMessage.success('模板更新成功');
    }

    // 清除暂存
    clearDraft();

    // 返回列表页
    router.push('/experiment-templates');
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败: ' + error.message);
  } finally {
    saving.value = false;
  }
}

// 取消
function handleCancel() {
  ElMessageBox.confirm(
    '确定要取消吗？未保存的更改将会丢失。',
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning',
    }
  )
    .then(() => {
      router.push('/experiment-templates');
    })
    .catch(() => {
      // 用户点击了取消
    });
}

// 返回
function handleBack() {
  handleCancel();
}
</script>

<style scoped lang="scss">
.template-edit-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background-color: #fff;
    border-bottom: 1px solid #e4e7ed;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .edit-tabs {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    margin: 0;

    :deep(.el-tabs__header) {
      margin: 0;
      padding: 0 24px;
      background-color: #fff;
      border-bottom: 1px solid #e4e7ed;
    }

    :deep(.el-tabs__content) {
      flex: 1;
      overflow: hidden;
    }

    :deep(.el-tab-pane) {
      height: 100%;
    }

    .tab-label {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 14px;
    }

    .tab-content {
      height: 100%;
      overflow: auto;

      &.yaml-view {
        display: flex;
        flex-direction: column;
        padding: 0;
        overflow: hidden;

        .yaml-toolbar {
          padding: 16px 24px;
          background-color: #f5f7fa;
          border-bottom: 1px solid #e4e7ed;
          flex-shrink: 0;
        }

        :deep(.yaml-editor-wrapper) {
          flex: 1;
          overflow: hidden;
        }
      }
    }
  }
}
</style>
